/**
 * @ author: 汪孟苹
 */
define(["jquery","bbcare","fu/app/comm/comm",
	"scprit/followup/app/question/imgCollection.servers.js",
	"scprit/followup/app/question/drawCanvas.js",
	"scprit/followup/app/question/question.servers.js",
	"scprit/followup/app/question/question.ui.js",
	"scprit/followup/app/comm/page/page.js"],
	function($,$bb,$comm,$imgCollectionServers,$drawCanvas,$questionServers,$questionUi,$page){
	var questionEvent = {};
    /**
     * input输入框上的图标出现与否根据输入框内有无内容
     */
	var iconShowByVal = function(obj,value){
		if(value != ""){
			obj.parent(".qaCard-inputGroup").addClass("input-group");
			obj.next().show();
		}else{
			obj.parent(".qaCard-inputGroup").removeClass("input-group");
			obj.next().hide();
		}
	}
    /**
     * input绑定input propertychange事件;遍历input
     * @description  qaCard-inputGroup为包裹带icon图标的input的div的class名;
     */
    var iconShow = function(){
    	$(".qaCard-inputGroup .input-group-btn").hide();
		$(".qaCard-inputGroup input").bind("input propertychange",function(){
			var value = $(this).val();
			iconShowByVal($(this),value);
		});
		$(".qaCard-inputGroup input").each(function(i){
			var value = $(".qaCard-inputGroup input").eq(i).val();
			iconShowByVal($(".qaCard-inputGroup input").eq(i),value);
		});
		$(".qaCard-inputGroup p.form-control-static").each(function(i){
			var value = $(this).html();
			iconShowByVal($(this),value);
		});
    }

	/**
	 * 根据出生日期和孕周计算预产期
	 */
	var getDueDateBygestation = function(bothDate,gestation){
		var daysDiff = 40*7 - gestation;
		var total = daysDiff*24*60*60*1000;
		var bothDate = new Date(bothDate);
		var bothMesc = bothDate.getTime();
		var dueDate = new Date(bothMesc + total);
		return $comm.getDateFormat(dueDate).date;
	}
	/**
	 * 将孕周展示在页面中
	 */
	var dateChange = function($bothDate,$dueDate,$gestation){
		var bothDate = $bothDate.val();
		var dueDate = $dueDate.val();
		if(bothDate && dueDate){
			var returnDateDiff = $comm.getGestation(bothDate,dueDate);
			$gestation.eq(0).val(returnDateDiff.weekActual);
			$gestation.eq(1).val(returnDateDiff.dayActual);
		}
	}
	/**
	 * 填出生日期和预产期或出生日期和孕周，可以自动带出预产期或孕周
	 */
	var funDateChange = function($bothDate,$dueDate,$gestation){
		$bothDate.bind('input porpertychange',function(){
			if($dueDate.val()==""){
				$dueDate.val($(this).val());
			}
			dateChange($bothDate,$dueDate,$gestation);
		});
		$dueDate.bind('input porpertychange',function(){
			if($bothDate.val()==""){
				$bothDate.val($(this).val());
			}
			dateChange($bothDate,$dueDate,$gestation);
		});	
		$gestation.change(function(){
			if($bothDate.val() != ""){
				var bothDate = $bothDate.val();
				var weeks = $gestation.eq(0).val();
				var days = $gestation.eq(1).val();
				var totalDays = Number(weeks*7) + Number(days);
				var dueDate = getDueDateBygestation(bothDate,totalDays);
				$dueDate.val(dueDate);
			}
		});
	}
	/**
	 * 填出生日期或预产期，可以自动带出另一个，根据生日期和预产期计算孕周（添加患者页面、门诊录入页面）
	 */
	var gestationComplex = function(){		
    	if( $(".qaCard-gestationComplex select") ){
    		var $date = $(".qaCard-gestationComplex input");
			var $gestation = $(".qaCard-gestationComplex select");
            funDateChange($date.eq(0),$date.eq(1),$gestation);
    	}	 
	}

	/**
	 * 填出生日期或预产期，可以自动带出另一个
	 */
	var funDateChangeSimple = function($bothDate,$dueDate){	
		$bothDate.bind('input porpertychange',function(){
			if($dueDate.val()==""){
				$dueDate.val($(this).val());
			}
		});
		$dueDate.bind('input porpertychange',function(){
			if($bothDate.val()==""){
				$bothDate.val($(this).val());
			}
		});	
	}
	/**
	 * 填出生日期或预产期，若另一个为空则带出另一个（添加患者页面、门诊录入页面）
	 */
	var gestationSimple = function(){		
    	if( $(".qaCard-gestationSimple input").length == 2 ){
    		var $date = $(".qaCard-gestationSimple input");
            funDateChangeSimple($date.eq(0),$date.eq(1));
    	}	 
	}

	/**
	 * 根据出生日期或预产期，计算出纠正胎龄/纠正年龄/年龄
	 */
	var calculateCorrectAge = function($bothDate,$dueDate,$correctAge){
		var bothDate = $bothDate.val();
		var dueDate = $dueDate.val();
		var presentDate = $comm.getCurTime().date;
		var label;
		if(bothDate && dueDate){
			var gestation = $comm.getGestation(bothDate,dueDate);
			var daysGestation = gestation.weekActual*7 + gestation.dayActual; // 孕周（单位天）
			var actualDays = $comm.dateDiff(bothDate,presentDate).days;
			var correctDays = $comm.dateDiff(dueDate,presentDate).days;
			var days;
			if(daysGestation < 37*7 && actualDays < 365*2){
				if(correctDays < 0){
					days = correctDays + 40*7;
					label = "纠正胎龄(天)";
				}else{
					days = correctDays;
					label = "纠正年龄(天)";
				}
			}else{
				days = actualDays;
				label = "年龄(天)";
			}
			$correctAge.val(days);
		}else{
			$correctAge.val("");
			label = "年龄(天)";
		}
		$correctAge.parents(".qaCard").find("label.control-label").html(label);
	}
	/**
	 * 填出生日期或预产期，可以自动带出另一个
	 */
	var funDateChangeCorrectAge = function($bothDate,$dueDate,$correctAge){	
		$bothDate.bind('input porpertychange',function(){
			if($dueDate.val()==""){
				$dueDate.val($(this).val());
			}
			calculateCorrectAge($bothDate,$dueDate,$correctAge);
		});
		$dueDate.bind('input porpertychange',function(){
			if($bothDate.val()==""){
				$bothDate.val($(this).val());
			}
			calculateCorrectAge($bothDate,$dueDate,$correctAge);
		});	
	}
	/**
	 * 填出生日期和预产期，可以自动带出纠正胎龄/纠正年龄/年龄
	 */
	var correctAge = function(){
		if( $(".qaCard-correctAge input[type=text]") ){
    		var $date = $(".qaCard-correctAge input[type=date]");
			var $correctAge = $(".qaCard-correctAge input[type=text]");
            funDateChangeCorrectAge($date.eq(0),$date.eq(1),$correctAge);
    	}	
	}
	
	/**
	 * 根据出生日期和预产期计算出孕周和年龄/纠正胎龄/纠正年龄
	 */
	var calculateOverallBirth = function($bothDate,$dueDate,$gestation,$correctAge){
		var bothDate = $bothDate.val();
		var dueDate = $dueDate.val();
		var presentDate = $comm.getCurTime().date;
		var label;
		if(bothDate && dueDate){
			var gestation = $comm.getGestation(bothDate,dueDate);
			$gestation.eq(0).val(gestation.weekActual);
			$gestation.eq(1).val(gestation.dayActual);
			var daysGestation = gestation.weekActual*7 + gestation.dayActual; // 孕周（单位天）
			var actualDays = $comm.dateDiff(bothDate,presentDate).days;
			var correctDays = $comm.dateDiff(dueDate,presentDate).days;
			var days;
			if(daysGestation < 37*7 && actualDays < 365*2){
				if(correctDays < 0){
					days = correctDays + 40*7;
					label = "纠正胎龄(天)";
				}else{
					days = correctDays;
					label = "纠正年龄(天)";
				}
			}else{
				days = actualDays;
				label = "年龄(天)";
			}
			$correctAge.val(days);
		}else{
			$correctAge.val("");
			label = "年龄(天)";
		}
		$correctAge.parents(".qaCard").find("label.control-label").html(label);
	}
	/**
	 * 出生日期、预产期、孕周改变时，其他都相应改变
	 */
	var funDateChangeOverallBirth = function($bothDate,$dueDate,$gestation,$correctAge){
		$bothDate.bind('input porpertychange',function(){
			if($dueDate.val()==""){
				$dueDate.val($(this).val());
			}
			calculateOverallBirth($bothDate,$dueDate,$gestation,$correctAge);
		});
		$dueDate.bind('input porpertychange',function(){
			if($bothDate.val()==""){
				$bothDate.val($(this).val());
			}
			calculateOverallBirth($bothDate,$dueDate,$gestation,$correctAge);
		});
		$gestation.change(function(){
			if($bothDate.val() != ""){
				var presentDate = $comm.getCurTime().date;
				var bothDate = $bothDate.val();
				var weeks = $gestation.eq(0).val();
				var days1 = $gestation.eq(1).val();
				var daysGestation = Number(weeks*7) + Number(days1);
				var dueDate = getDueDateBygestation(bothDate,daysGestation);
				$dueDate.val(dueDate);
				var actualDays = $comm.dateDiff(bothDate,presentDate).days;
				var correctDays = $comm.dateDiff(dueDate,presentDate).days;
				var days;
				if(daysGestation < 37*7 && actualDays < 365*2){
					if(correctDays < 0){
						days = correctDays + 40*7;
						label = "纠正胎龄(天)";
					}else{
						days = correctDays;
						label = "纠正年龄(天)";
					}
				}else{
					days = actualDays;
					label = "年龄(天)";
				}
				$correctAge.val(days);
				$correctAge.parents(".qaCard").find("label.control-label").html(label);
			}
		});
	}
	/**
	 * 填出生日期和预产期，可以自动带出孕周、纠正胎龄/纠正年龄/年龄
	 */
	var overallBirth = function(){
		var $date = $(".qaCard-overallBirth input[type=date]");
		var $gestation = $(".qaCard-overallBirth select");
		var $correctAge = $(".qaCard-overallBirth input[type=text]");
		funDateChangeOverallBirth($date.eq(0),$date.eq(1),$gestation,$correctAge);
	}

	/**
	 * 生长发育题型
	 */
	// 自动填入百分位内容（根据onGrowPercentile方法中的id和返回的内容）
    var valuationPercentile = function(dom,value){
        dom.val(value);
    } 

    // 自动填入日增长
    var valuationIncr = function(dom,name,preTestTime,value,testTime,unit,data){	// data是返回的上一次录入的数据的，并不是当前随访的上一次
    	var result;
		var days = Number($comm.dateDiff(preTestTime,testTime).days);
		console.log(days);
    	if(days > 0){
	    	if( name.indexOf("-") > -1 ){   // 单独处理体重单位（kg与g）
		        name = name.split("-")[0];
			}
			result = (value - data[name]) / days;
			
			if (value.indexOf('.') === -1) {
				value = value + '.0'
			}

			var n = $comm.getDecimalPlaces(value) + 1;
	    	if(unit == "g"){
				result = result*1000;
				n = n - 3;
			}
			result = result * 7;
	        result = result.toFixed(n);
	        valuationPercentile(dom,result);
		}
    }

	// 根据填入的生长数值请求到对应的百分位
    var onGrowPercentile = function(){
		var data = $(this).data("value");
        var value = $(this).val();
        var calcType = $(this).attr("calcType");
        var unit = $(this).attr("unit");
		var name = $(this).attr("name");
        var growPerDom = $(this).parents(".qaCard").next(".qaCard").find("input");
		var lastGrowDom = $(this).parents(".qaCard").next(".qaCard").next(".qaCard").find("input");
        if(value != "") {
        	if( calcType == "00001" && unit == "g"){
	        	var n = $comm.getDecimalPlaces(value) + 3;
	        	value = (value / 1000).toFixed(n);
	        }
            var type = $(this).attr("calcType");
            var testTime = $("input[name='finishDate']").val();
            var params = {
                type: type,
                userId: data.patientId,
                values: value,
                testTime: testTime,
            };
            var params2 = {
                followQueueId:data.followQueueId,
				ptTaskId:data.preTaskId
            };
            $questionServers.ajaxGrowthPercentiles(params,valuationPercentile,growPerDom);
			console.log(lastGrowDom);
            if(lastGrowDom) $questionServers.ajaxLastGrowth(params2,valuationIncr,lastGrowDom,name,value,testTime,unit);	// 存在lastGrowDom为复杂题型，不存在为简单题型
        }else{
            valuationPercentile(growPerDom,"");
            if(lastGrowDom) valuationPercentile(lastGrowDom,"");
        }
    }

    // 请求生长曲线成功后的回调方法
    var getGrowthCurveCallback = function(data,className,label,gender){
        $questionUi.curve(data,className,label,gender,1);
    }
	// 生长曲线图
	var onGrowCurve = function(){
		var $input = $(this).parent().prev();
		if($input[0].tagName.toLocaleLowerCase()=="input"){
			var testTime = $("input[name='finishDate']").val();
			var value = $(this).parent().prev().val();
		}else{
			var testTime = $("p[name='finishDate']").text();
			var value = $(this).parent().prev().text();
		}
        var options = $(this).data();
		var type = $(this).parent().prev().attr("calcType");
		var label = $(this).parent().parent(".qaCard-inputGroup").prev().text();
        var calcType = $(this).parent().prev().attr("calcType");
        var unit = $(this).parent().prev().attr("unit");
        if( calcType == "00001" && unit == "g"){
        	var keepDecimal = Math.pow(10,4);
        	value = Math.round(value / 1000 * keepDecimal) / keepDecimal;
        }
		var params = {
			scoreType:"01",	// 百分位曲线
			type: type,
			userId:	options.patientId,
			values: value,
            testTime: testTime,
		};
		var className = "curveModal";
		$comm.modal({
			"className": className,
            "tit": "曲线图",
		},function(){
	        $questionServers.ajaxGrowthCure(params,getGrowthCurveCallback,className,label,options.gender);
	        $("."+ className).modal('show'); 
        });
	};

	// 生长发育题型
	var growth = function(params){
		// 百分位、日增长
		$(".qaCard-inputGroup input").unbind("blur");
        $(".qaCard-inputGroup input").data({
        	"value":{
	        	"patientId":params.patientId,
	        	"preTaskId":params.preTaskId,
	        	"followQueueId":params.followQueueId
	        },
	        "fun":onGrowPercentile
    	});
        $(".qaCard-inputGroup input").blur(onGrowPercentile);
        // 曲线图
        $(".qaCard-inputGroup .input-group-btn button").unbind("click");
        $(".qaCard-inputGroup .input-group-btn button").data({
            patientId: params.patientId,    // 为了计算身高体重百分位
            gender:params.gender
        });
        $(".qaCard-inputGroup .input-group-btn button").click(onGrowCurve);
	}

	/**
	 * 点击根据手机号+ptSchemeId查询成功后的回调，重新渲染问卷
	 */
	var getPatientcallback = function(data,params,obj,options){
		var result = data.rows[0];
		if(options.callback && typeof options.callback == "function"){
			options.callback(options.params,result);
		}
	}
	/**
	 * 点击根据手机号码查询到的患者，重新渲染问卷
	 */
	var getPatientsByPhonecallback = function(data,params,obj,options){
		if(data.total > 0){
			obj.next(".patientsList").css({"display":"block"});
			$questionUi.patientsByPhone({
				dom:obj.next(".patientsList"),
				list:data.rows
			});
			$(document).click(function(){
				obj.next(".patientsList").css({"display":"none"});
			});
			obj.next(".patientsList").find(".addPatientBtn").click(function(){
				obj.next(".patientsList").css({"display":"none"});
			});
			obj.next(".patientsList").find(".patient-item").unbind("click");
			obj.next(".patientsList").find(".patient-item").click(function(){
				var ptSchemeId = $(this).attr("ptSchemeId");
				params = $.extend(params,{ "ptSchemeId":ptSchemeId });
				$questionServers.ajaxPatientsByPhone(params,getPatientcallback,obj,options);
			});
		}else{
			obj.next(".patientsList").css({"display":"none"});
		}
	}
	/**
	 * 根据手机号码查询患者
	 */
	var onPatientsByPhone = function(){
		if( $bb.getIocalStorage("version") == "online" ){
			var options = $(this).data("paramsByPhone");
			if(!options.params.schemeBusiType) options.params.schemeBusiType = 0; // 默认0
			var followQueueId; 
			if( options.params.followQueueId ){
				followQueueId = options.params.followQueueId;
			}else if( options.params.queueId ){
				followQueueId = options.params.queueId;
			}
			var params = {
				"followQueueId": followQueueId,
				"schemeBusiType":options.params.schemeBusiType
			};
			var qId = $(this).attr("name"); // 问题id
			var value = $(this).val();
			if($.trim(value) != ''){
				switch(qId){
					case "Pub1100001":
						var curParam = {"phoneNum": value};
						break;
					case "Pub1100002":
						var curParam = {"patientName": value};
						break;
					case "Pub12x00007":
					case "Pub12x00008":
					case "341200007":
						var curParam = {"hisNo": value};
						break;
				}
				params = $.extend(params,curParam);
				$questionServers.ajaxPatientsByPhone(params,getPatientsByPhonecallback,$(this),options);
			}else{
				$(this).next(".patientsList").css({"display":"none"});
			}
		}
	};
	/**
	 * question_autocomplete题型（输入手机号码带出患者列表）
	 */
	var getPatientsByPhone = function(options){
		$(".qaCard-autocomplete input").unbind("input propertychange");
	    $(".qaCard-autocomplete input").data({"paramsByPhone":options});
	    $(".qaCard-autocomplete input").bind("input propertychange",onPatientsByPhone);
	};
	/**
	 * question_radioInput题型（根据单选结果显示输入框）
	 */
	var radioInput = function(){
		$(".qaCard-radioInput").each(function(i){
			var value = $(this).find(".radio input:radio:checked").eq(0).val();
			var relevantText = $(this).attr("relevantText");
			if(value != relevantText){
				$(this).find(".qaCard").last().css({"display":"none"});
			}
		});
		$(".qaCard-radioInput .radio input:radio").bind("change",function(){
			var value = $(this).val();
			var relevantText = $(this).parents(".qaCard-radioInput").attr("relevantText");
			if(value == relevantText){
				$(this).parents(".qaCard").next().css({"display":"block"});
			}else{
				$(this).parents(".qaCard").next().css({"display":"none"});
				$(this).parents(".qaCard").next().find("input").val("");
			}
		});
	}
	/**
	 * question_radioWithInput题型 单选加输入题型(一个id)
	 */
	var radioWithInput = function(){
		$(".qaCard-radioWithInput").each(function(i){
			var value = $(this).find(".radio input:radio:checked").eq(0).val();
			var relationKey = $(this).attr("relationKey");
			if(value != relationKey){
				$(this).find(".qaCard-radioWithInput-input").hide();
			}
		});
		$(".qaCard-radioWithInput .radio input:radio").bind("change",function(){
			var value = $(this).val();
			var relationKey = $(this).parents(".qaCard-radioWithInput").attr("relationKey");
			if(value == relationKey){
				$(this).parents(".qaCard-radioWithInput").find(".qaCard-radioWithInput-input").show();
			}else{
				$(this).parents(".qaCard-radioWithInput").find(".qaCard-radioWithInput-input").hide();
				$(this).parents(".qaCard-radioWithInput").find(".qaCard-radioWithInput-input").find("input").val("");
			}
		});
	}
	/**
	 * question_checkboxInput题型（根据复选结果显示输入框）
	 */
	var checkboxInput = function(){
		$(".qaCard-checkboxInput").each(function(i){
			var checkboxDom = $(this).find(".checkbox input:checkbox:checked");
			var relevantText = $(this).attr("relevantText");
			var flag = false;
			checkboxDom.each(function(j){
				if( checkboxDom.eq(j).val() == relevantText ){
					flag = true;
					return false;
				}
			});
			if(!flag) $(this).find(".qaCard").last().css({"display":"none"});
		});
		$(".qaCard-checkboxInput .checkbox input:checkbox").bind("change",function(){
			var value = $(this).val();
			var relevantText = $(this).parents(".qaCard-checkboxInput").attr("relevantText");
			if(value == relevantText){
				if( $(this).is(':checked') ){
					$(this).parents(".qaCard").next().css({"display":"block"});
				}else{
					$(this).parents(".qaCard").next().css({"display":"none"});
					$(this).parents(".qaCard").next().find("input").val("");
				}
			}
		});
	}
	/**
	 * question_checkboxWithInput题型 复选加输入题型(一个id)
	 */
	var checkboxWithInput = function(){
		$(".qaCard-checkboxWithInput").each(function(i){
			var checkboxDom = $(this).find(".checkbox input:checkbox:checked");
			var relationKey = $(this).attr("relationKey");
			var flag = false;
			checkboxDom.each(function(j){
				if( checkboxDom.eq(j).val() == relationKey ){
					flag = true;
					return false;
				}
			});
			if(!flag) $(this).find(".qaCard-checkboxWithInput-input").hide();
		});
		$(".qaCard-checkboxWithInput .checkbox input:checkbox").bind("change",function(){
			var value = $(this).val();
			var relationKey = $(this).parents(".qaCard-checkboxWithInput").attr("relationKey");
			if(value == relationKey){
				if( $(this).is(':checked') ){
					$(this).parents(".qaCard").find(".qaCard-checkboxWithInput-input").show();
				}else{
					$(this).parents(".qaCard").find(".qaCard-checkboxWithInput-input").hide();
					$(this).parents(".qaCard").find(".qaCard-checkboxWithInput-input").find("input").val("");
				}
			}
		});
	}
	/**
	 * 单选框可点击取消选中
	 */
	var cancelRadioChecked = function(){
		$("input:radio").parent().mousedown(function(event){
			event = event || window.event;
		    var target = event.target || event.srcElement;
		    if($(target).is('input')){ // 点击的是 input
		    	target.previousValue = target.checked;
		    }else{	// 点击的是 input的父级label
		    	target.control.previousValue = target.control.checked;
		    }
		});
		$("input:radio").parent().click(function(event){
			event = event || window.event;
		    var target = event.target || event.srcElement;
		    if($(target).is('input')){
	        	if (target.previousValue) {
		            target.checked = false;
	        	}
			}else{
				return;
			}
		});
	}
	/**
	 * 省市区三级联动初始化
	 */
	var addressInit = function(val,nextVal,$parent,data,$self){
		if(val){
			var selfId = $parent.find("option:selected").attr("selfId");
			var h = '<option value="" selfId="0"></option>';
			if ( selfId > 0 ) {
				for (var i = 0; i < data.length; i++) {
					if (data[i].parent_id == selfId ){
						if(data[i].self_name == nextVal){
							h += '<option value="'+data[i].self_name+'" selected="selected" selfId="'+data[i].self_id+'">'+ data[i].self_name +'</option>';
						}else{
							h += '<option value="'+data[i].self_name+'" selfId="'+data[i].self_id+'">'+ data[i].self_name +'</option>';
						}
					}
				}
				$self.html(h);
			}
		}
	};
	/**
	 * 省市区三级联动select变化时相关联
	 */
	var onChangeSelect = function(){
		var options = $(this).data("value");
		var data = options.data, $dom = options.$dom;
		var selfId = $(this).find("option:selected").attr("selfId");
		var h = '<option value="" selfId="0"></option>';
		if ( selfId > 0 ) {
			for (var i = 0; i < data.length; i++) {
				if (data[i].parent_id == selfId ){
					h += '<option value="'+data[i].self_name+'" selfId="'+data[i].self_id+'">'+ data[i].self_name +'</option>';
				}
			}
			$dom.html(h);
		}
	}
	/**
	 * 省市区三级联动
	 */
	var address = function(){
		$(".qaCard-address").each(function(i){
			var $select = $(this).find(".control-input > div > select");
			var $province = $select.eq(0), $city = $select.eq(1), $county = $select.eq(2);
			$.getJSON('scprit/followup/data/position/position.json',function(data){
				var province = data.province, city = data.city, county = data.county;
				var val1 = $province.attr("val"), val2 = $city.attr("val"), val3 = $county.attr("val");
				var h1 = '<option value="" selfId="0"></option>';
				for (var i = 0; i < province.length; i++) {
					if(province[i].self_name == val1){
						h1 += '<option value="'+province[i].self_name+'" selected="selected" selfId="'+province[i].self_id+'">'+ province[i].self_name +'</option>';
					}else{
						h1 += '<option value="'+province[i].self_name+'" selfId="'+province[i].self_id+'">'+ province[i].self_name +'</option>';
					}
				}
				$province.html(h1);
				addressInit(val1,val2,$province,city,$city);
				addressInit(val2,val3,$city,county,$county);
				$province.data({"value":{"data":city,"$dom":$city}})
				$province.bind("change",onChangeSelect);
				$city.data({"value":{"data":county,"$dom":$county}})
				$city.bind("change",onChangeSelect);
	        });
		});
	}
	/**
	 * 1、高危测评
	 */
	// 保存评估结果后的回调函数
	var saveAssessResultCallBack = function (data,params){
		var data = data.map;
        var str = '共计 '+ data.lens +' 项，'+ data.scoresTotal +'分，属于'+ data.level +'；';
       	var ques = '（ ';
       	for (var i = 0; i < data.result.length; i++) {
       		ques += data.result[i].ques + '； ';
       	}
       	ques += ' ）';
       	params.textareaDom.val(str + ques);
       	$("." + params.className).modal('hide');
    };
	// 高危孕产妇问卷计算评分
	var onCountScore = function(){
		var params = $(this).data("params");
		var hashMapQues = $questionServers.getAssesshighriskResultData($("." + params.className + " .modal-body"));
        params = $questionServers.handleAssessResult(params,hashMapQues);
        if(params) $questionServers.saveAssessResult(params,saveAssessResultCallBack);
	}
	// 高危孕产妇问卷重置
	var onReset = function(){
		var params = $(this).data("params");
		$("."+ params.className + " .modal-body input:checked").each(function(){
            $(this).removeAttr("checked");
        });
	}
	// 获取高危孕产妇问卷后的回调函数
	var highriskPregnantAssessCallBack = function(data,params,lastScore){
		var className = "assessModal";
		$.extend(params,{"className":className});
		$comm.modal({
			"className": className,
            "size": "modal-lg",
            "tit": "高危儿孕产妇评分",
            "showModalFooter":true
		},function(){
			$questionUi.highRiskInit({
				"dom":$("." + className + " .modal-body"),
				"list":$questionServers.highriskPregnantData(data,lastScore)
			});
			$questionUi.assessFooterInit({
				"dom":$("." + className + " .modal-footer"),
				"flag":true	//重置
			});
			$("." + className).modal("show");
			$("." + className +" .modal-footer .btn-primary").data({"params":params});
			$("." + className +" .modal-footer .btn-primary").click(onCountScore);
			$("." + className +" .modal-footer .btn-default").data({"params":params});
			$("." + className +" .modal-footer .btn-default").click(onReset);
		});
	}
	/**
	 * 2、Alberta婴幼儿运动量问卷
	 */
	// 保存评估结果后的回调函数(Alberta婴幼儿运动量问卷)
	var saveAssessAIMSResultCallBack = function(data,params){
		var str = "Alberta：总得分" + data.total.totalScore + "分；超越了同年龄  " + data.total.percent + "  的婴儿";
		params.textareaDom.val(str);
       	$("." + params.className).modal('hide');
	}
	// Alberta婴幼儿运动量问卷计算评分
	var onAIMSCountScore = function(){
		var params = $(this).data("params");
		var data = $questionServers.getAssessAIMSResultData($("." + params.className + " .modal-body"));
		params = $.extend(params,{"postionIds":data,"postionScores":""});
        if(params) $questionServers.saveAssessResult(params,saveAssessAIMSResultCallBack);
	}
	// Alberta婴幼儿运动量模态框问卷 点击.asCard-aims-tab切换
	var onAsCardAimsTabSelect = function(){
		var index = $(this).index();
		$(this).addClass("checking").siblings().removeClass("checking");
		$(this).parent().next().children().eq(index).show().siblings().hide();
	}
	// Alberta婴幼儿运动量模态框问卷 选中某一个.asCard-aims
	var onAsCardAimsCheck = function(){
		var checkFlag = $(this).hasClass("active");
		if( !checkFlag ){
			$(this).addClass("active");
			$(this).find(".asCard-aims-symbol i").addClass("fa-check-circle").removeClass("fa-minus-circle");
		}else{
			$(this).removeClass("active");
			$(this).find(".asCard-aims-symbol i").addClass("fa-minus-circle").removeClass("fa-check-circle");
		}
	}
	// 获取Alberta婴幼儿运动量表问卷后的回调函数
	var aIMSAssessCallBack = function(data,params,baseParams,lastScore){
		var className = "assessModal";
		$.extend(params,{"className":className});
		$comm.modal({
			"className": className,
            "size": "modal-lg",
            "tit": "Alberta婴幼儿运动量评分",
            "showModalFooter":true
		},function(){
			$("." + className + " .modal-body").css({"backgroundColor":"#EAEFF5"});
			$questionUi.assessFooterInit({
				"dom":$("." + className + " .modal-footer"),
			});
			$questionUi.aimsInit({
				"dom":$("." + className + " .modal-body"),
				"list":$questionServers.aimsData(data,lastScore)
			});
			$("." + className).modal("show");
			// 点击tab切换
			$("." + className + " .asCard-aims-tab > div").click(onAsCardAimsTabSelect);
			$("." + className + " .asCard-aims-tab > div").first().click();
			// 进行选择
			$("." + className + " .asCard-aims").click(onAsCardAimsCheck);
			// 保存
			$("." + className + " .modal-footer .btn-primary").data({"params":params});
			$("." + className + " .modal-footer .btn-primary").click(onAIMSCountScore);
		});
	}
	/**
	 * 公共评估方法：
	 */
	var assess = function(params,url,tit){
		var className = "assessModal";
		$.extend(params,{"className":className});
		$comm.modal({
			"className": className,
            "size": "modal-lg",
            "tit": tit,
		},function(){
			if(params.examinationPaperName == "FHRIS"){//高危儿五项去除padding;
				$("." + className).find(".modal-body").css("padding","0px");
			}
			$("." + className).modal("show");
			$bb.setSessionStorage(params.examinationPaperName, JSON.stringify(params));
			$.get(url,function(html){
				$("." + className + " .modal-body").html(html);
			});
		});
	}
	/**
	 * 测评 评估
	 */
	var textareaAssess = function(params){
		$(".qaCard-textareaAssess .btn-Assess.clickable").unbind("click");
		$(".qaCard-textareaAssess .btn-Assess.clickable").click(function(){ //clickable为状态为可写时按钮的类名
			if( $bb.getIocalStorage("version") == "online" ){
				var assessType = $(this).attr("assessType");
		        var textareaDom = $(this).prev("textarea");
				var textareaName = $(this).prev("textarea").attr("name");
				$.extend(params,{"examinationPaperName":assessType,"textareaDom":textareaDom,"textareaName":textareaName});
		        switch (assessType) {
	    			case "HighriskPregnant":
	    				$questionServers.getAssessQuest(params,highriskPregnantAssessCallBack);
	    				break;
	    			case "AIMS":
	    				$questionServers.getAssessQuest(params,aIMSAssessCallBack);
	    				break;
	    			case "nbna":
	    				assess(params,'page/evaluatingPublicPages/html/nbnaAssessment.html','行为神经(NBNA)评分');
	    				break;
					case "GMS":
						assess(params,"page/evaluatingPublicPages/html/gms/gmsDetail.html","GMs评估");
						break;
					case "FHRIS":
						assess(params,'page/evaluatingPublicPages/html/fiveHighRiskInfants/fiveHighRiskInfantsQuestionnaire.html','高危儿筛查五项');
						break;
	    		}
	    	}else{
	    		$bb.toastShow("离线版暂不支持该题型！",1500);
	    	}
		});
	}
	/**
	 * 勾选复选框决定是否显示相关联的题目
	 */
	var checkboxRelation = function(){
		var dom = $(".qaCard[relationId]"); // 表单里带relationId的dom元素
		// 初始化
		$(".qaCard-checkboxRelation").each(function(i){
			var checkboxDom = $(this).find(".checkbox input:checkbox");
			var notCheckedDom = checkboxDom.not("input:checked");
			notCheckedDom.each(function(j){
				var rId = notCheckedDom.eq(j).attr("rId");
				dom.each(function(p){
					if(dom.eq(p).attr("relationId") == rId){
						dom.eq(p).hide();
					}
				});
			});
		});
		$(".qaCard-checkboxRelation .checkbox input:checkbox").bind("change",function(){
			var This = $(this);
			var rId = This.attr("rId");
			dom.each(function(j){
				if(dom.eq(j).attr("relationId") == rId){
					if( This.is(':checked') ){
						dom.eq(j).show();
					}else{
						dom.eq(j).hide();
					}
				}
			});
		});
	}
	/**
	 * 勾选单选框决定是否显示相关联的题目
	 */
	var domHideHasClass = function(dom,j,flag){
		if( dom.eq(j).hasClass("qaCard-radioRelation") ){
	 		dom.eq(j).find(".radio input:radio").each(function(){
	 			if( $(this).attr("rId") != "" ){
	 				var rId1 = $(this).attr("rId");
					dom.each(function(p){
						if(dom.eq(p).attr("relationId") == rId1){
							if( flag == "show" ){
								dom.eq(p).show();
							}else if( flag == "hide" ){
								dom.eq(p).hide();
							}
						}
					});
	 			}
			});
	 	}
	}
	var onRadioRelation = function(event){
		var dom = $(this).data("dom");
		var This = $(this);
		var rId = This.attr("rId");
		dom.each(function(j){
			if(dom.eq(j).attr("relationId") == rId){
				// event.target.previousValu 取消单选框选中状态时设置的
				if( event.target.previousValue ){
				 	dom.eq(j).hide();
				 	domHideHasClass(dom,j,"hide");
				}else{
				 	dom.eq(j).show();
				 	if( dom.eq(j).hasClass("qaCard-radioRelation") ){
				 		dom.eq(j).find(".radio input:radio:checked").each(function(){
				 			if( $(this).attr("rId") != "" ){
				 				var rId1 = $(this).attr("rId");
								dom.each(function(p){
									if(dom.eq(p).attr("relationId") == rId1){
										dom.eq(p).show();
									}
								});
				 			}
						});
				 	}
				}
			}else{
				This.parents(".qaCard-radioRelation").find(".radio input:radio").each(function(){
					if( dom.eq(j).attr("relationId") == $(this).attr("rId") ){
					 	dom.eq(j).hide();
					 	domHideHasClass(dom,j,"hide");
					}
				});
			}
		});
	}
	var radioRelation = function(){
		var dom = $(".qaCard[relationId]"); // 表单里带relationId的dom元素
		// 初始化
		$(".qaCard-radioRelation").each(function(i){
			var radioDom = $(this).find(".radio input:radio");
			var notCheckedDom = radioDom.not("input:checked");
			notCheckedDom.each(function(j){
				var rId = notCheckedDom.eq(j).attr("rId");
				dom.each(function(p){
					if(dom.eq(p).attr("relationId") == rId){
						dom.eq(p).hide();
						domHideHasClass(dom,j,"hide");
					}
				});
			});
		});
		$(".qaCard-radioRelation .radio input:radio").unbind("click");
		$(".qaCard-radioRelation .radio input:radio").data({"dom":dom});
		$(".qaCard-radioRelation .radio input:radio").bind("click",onRadioRelation);
	}
	/**
	 * 可折叠的题组
	 */
	var collapse = function(){
		$(".qaCard-groupCollapse .qaCard-subtit").each(function(i){
			var collapse = $(this).attr("collapse");
			if(collapse == "true"){
				$(this).next(".qaCard-groupCollapse-content").hide();
			}else{
				$(this).next(".qaCard-groupCollapse-content").show();
			}
		});
		$(".qaCard-groupCollapse .qaCard-subtit").click(function(){
			var collapse = $(this).attr("collapse");
			if(collapse == "true"){
				$(this).attr("collapse","false");
				$(this).find("i.fa-plus-square-o").addClass("fa-minus-square-o").removeClass("fa-plus-square-o");
				$(this).next(".qaCard-groupCollapse-content").show();
			}else{
				$(this).attr("collapse","true");
				$(this).find("i.fa-minus-square-o").addClass("fa-plus-square-o").removeClass("fa-minus-square-o");
				$(this).next(".qaCard-groupCollapse-content").hide();
			}
		});
	}
	/**
	 * 上传文件成功后的回调函数
	 */
	 var uploadMultiFileCallBack = function(status, params, inputDom){
		if( status == 200 ){
			$("#"+inputDom.id).attr("data-value",params.imgUrl);
			$("#"+inputDom.id).attr("style","background:url(" + params.imgUrl + ") no-repeat center;background-size:cover")
			$("#" + inputDom.id + " .progress-pic > div").html('<i class="fa fa-check-circle" aria-hidden="true"></i>')
			$(".qaCard-pictures .picture").click(onPhotoZoomPro)
		}else{
			$("#"+inputDom.id).remove();
		}
		inputDom.obj.value = "";
	}
	// 请求policy成功后的回调函数
	// var ajaxPolicyCallBack = function(params,policy){
	// 	var fd = new FormData();
    // 	var filename = $comm.random(5) + $comm.timestamp() + $comm.getSuffix(params.file.name);
        
    //     fd.append('key', policy.dir + filename);  //存储在oss的文件路径
    //     fd.append('policy', policy.policy);  //policy
    //     fd.append('OSSAccessKeyId', policy.accessId);  //accessKeyId
    //     fd.append('success_action_status', "200");  //成功后返回的操作码
    //     fd.append('Signature', policy.signature);   //签名
    //     fd.append("file",params.file);
    //     if( !params.id ){
	//         var url = window.URL.createObjectURL(params.file);
	//     	var id = "picture_" + $comm.timestamp() + "_" + $comm.random();
	//         var h = '<div id="'+ id +'" class="picture" style="background:url(' + url + ') no-repeat center;background-size:cover">'+
	//             '   <div class="progress-pic"><div></div></div>'+
	//             '</div>';
	//         $(params.obj).parents(".qaCard-uploadBtn").before(h);
    //     }
    //     $.extend(params,{
    //     	"url":policy.host,
    //     	"fd":fd,
    //     	"imgUrl":policy.host + policy.dir + filename,
    //     	"id":id,
    //     });
    //     $questionServers.uploadFile(params,uploadMultiFileCallBack);
	// }

	var ajaxPolicyCallBack = function(params,policy){
		var id, url
		if ( !params.id ) {
			url = window.URL.createObjectURL(params.file);
			id = "picture_" + $comm.timestamp() + "_" + $comm.random();
			var h = '<div id="'+ id +'" class="picture" style="background:url(' + policy.imgUrl + ') no-repeat center;background-size:cover">'+
				'   <div class="progress-pic"><div style="width: 100%"></div></div>'+
				'</div>';
			$(params.obj).parents(".qaCard-uploadBtn").before(h);
		}
		params.url = url
		params.id = id
		uploadMultiFileCallBack(200, policy, params)
	}

    var addPictures = function(obj){
    	if( $bb.getIocalStorage("version") == "online" ){
    		if(obj.value != null && obj.value != ""){
		    	var typeStr = "image/jpg, image/png, image/gif, image/jpeg";
		    	var files = obj.files;
		    	for (var i = 0; i < files.length; i++) {
		    		if(typeStr.indexOf(files[i].type) == -1){
				        $bb.toastShow("请上传格式为jpg、png、gif、jpeg的图片！");
				        return;
				    }
				    if (files[i].size >= 1024*1024*10) {
				        $bb.toastShow("上传的文件不能大于10M！");
				        return;
				　　}
			    	// 直接上传到oss
			    	var params = {
			    		"obj":obj,
			    		"file":files[i],
			    	};
			    	$questionServers.ajaxPolicy(params,ajaxPolicyCallBack);
		    	}
	    	}
	    }else{ // 离线版
    		$bb.toastShow("离线版暂不支持上传图片！");
		}
    };

    /**
     * 放大图片(question_uploadPictures、question_sudokuPictures)
     */
    var onPhotoZoomPro = function(e){
    	e.stopPropagation();
    	var url = $(this).attr("data-value");
    	var className = "PhotoZoomProModal";
		$comm.modal({
			"tit":"图片放大",
			"className":className
		},function(){
			var h = '<img src="'+url+'">';
			$("." + className + " .modal-body").append(h);
			var realWidth;//真实的宽度
        	var _w = parseInt($(window).width());//获取浏览器的宽度
        	var _h = parseInt($(window).height());//获取浏览器的宽度
			$("<img/>").attr("src", url).load(function() {
                realWidth = this.width + 30 + 2 + 7;
                if(realWidth >= _w){
                   $("." + className + " .modal-dialog").css({"width":"100%"});
                }else{
                   $("." + className + " .modal-dialog").css({"width":realWidth});
                }
                $("." + className + " .modal-body").css({"max-height": _h - 111});
            });
		});
		$("."+className).modal("show");
    }

    /**
     * 删除图片（实际是在问卷里删除该图片的网址）
     */
    var onDelPicture = function(){
    	$(this).parents(".picture").remove();
    }
 
	/**
	 * 上传图片（多个）
	 */
	var uploadPictures = function(){
		$(".qaCard-pictures .qaCard-uploadBtn input[type=file]").change(function(){
			addPictures(this);
		});
		$(".qaCard-pictures .picture").click(onPhotoZoomPro);
		$(".qaCard-pictures .picture .picture-del-box").click(function(){
			return false;
		});
		$(".qaCard-pictures .picture").mouseenter(function(){
			$(this).find(".picture-del-box").slideDown();
			$(this).find(".picture-del").click(onDelPicture);
		}).mouseleave(function(){
			$(this).find(".picture-del-box").slideUp();
		});
	}
	/**
	 * question_karteName题型 门诊记录名题型
	 */
	var karteName = function(){
		$(".qaCard-karteName input.form-control").each(function(){
			$(this).bind("input",function(){
				var val = $(this).val();
				if( $("#specialNurseContentTit").length == 1 ){
					$("#specialNurseContentTit").html(val);
				};
			});
		});
	}

	/**
	 * 影像处理_添加
	 */
	var imageProcessingAdd = function(params){
		var className = "imageProcessingModal";
		var classIdList = JSON.parse($(params.dom).attr("deviceTypeId"));
		var diseaseTypeId = JSON.parse($(params.dom).attr("diseaseTypeId"));
		var manualTypeId = JSON.parse($(params.dom).attr("manualTypeId"));
		params.className = className;
		params.diseaseTypeId = diseaseTypeId;
		params.manualTypeId = manualTypeId;
		$comm.modal({
			"tit":"添加影像",
			"size":"modal-lg",
			"className":className
		},function(){
			//获取影像设备列表：
			$imgCollectionServers.getEquipList({"classIdList":classIdList},getEquipListCallback,params);
		});
	}
	/*
	 * 查询影像设备列表的 回调：
	 * */
	//影像设备列表数据处理：
	var addImgEquipList_dealFn = function(data){
		var arr = [];
		for(var i = 0; i<data.classList.length;i++){
			var classId = data.classList[i].classId;
			var equipList = data.classList[i].equipList;
			for(var j = 0;j < equipList.length ; j++){
				if (i == 0){equipList[j].show = true;}
				equipList[j].classId = classId;
				arr.push(equipList[j]);
			}
		}
		return arr;
	}
	var getEquipListCallback = function(data,infoParams){
		var equipArrList = addImgEquipList_dealFn(data.data);
		var modalParams = infoParams;
		infoParams.equipList = data.data.classList;
		infoParams.equipNumberList = equipArrList;
		$questionUi.addImageProcessingInit({
			"dom":$("#modalBox ." + infoParams.className + " .modal-body"),
			"data":infoParams
		});
		$("#modalBox ." + modalParams.className).modal("show");
		delete infoParams.equipList;
		delete infoParams.equipNumberList;

		var imgList,fileList,nameList;
		infoParams.imgList = [];
		infoParams.fileList = [];
		infoParams.nameList = [];
		//不同的影像设备下的设备编号展示：
		$("#addImgEquipType").off("click","label");
		$("#addImgEquipType").on("click","label",function(){
			var classId = $(this).attr("classId");
			if(classId){
				$(".manual-hide").css("display","block");
				$('#equipType-checkbox label').css("display","none");
				$('#equipType-checkbox label input').removeAttr("checked");
				$('#equipType-checkbox .addImg_equip_'+classId).css("display","inline-block");
				$('#equipType-checkbox .addImg_equip_'+classId).find("input").prop("checked","true");
			}else{
				$(".manual-hide").css("display","none");
			}
			
		});
		
		//查询按钮：
		$("#modalBox").off("click","#addImg_searchBtn");
		$("#modalBox").on("click","#addImg_searchBtn",function(){
			imgList = [];
			fileList = [];
			nameList = [];
			infoParams.imgList = [];
			infoParams.fileList = [];
			infoParams.nameList = [];
			infoParams.page = 1;//加载第一页；
			infoParams.rows = 8;//每一页展示个数；
			addImg_searchBtn(infoParams);
		});
		$("#addImg_searchBtn").click();

		//手动上传：
		$("#modalBox").off("change","#addImg_manualUploadBtn input[type='file']");
		$("#modalBox").on("change","#addImg_manualUploadBtn input[type='file']",function(){
			infoParams.dom = this;
			addImg_manualUpload(infoParams);
		});

		//“确定”：
		$("#modalBox").off("click","#addImg_autoUploadBtn");
		$("#modalBox").on("click","#addImg_autoUploadBtn",function(){
			infoParams.dom = this;
			addImg_autoUpload(infoParams);
		});

		//图片的点选：
		$("#modalBox").off("click","#add-imageProcessing-imageBox li img");
		$("#modalBox").on("click","#add-imageProcessing-imageBox li img",function(){
			var isChecked = $(this).attr("isChecked");//1未选中，2，选中
			var srcId = $(this).attr("srcId");
			var imgUrl = $(this).attr("imgUrl"),fileName = $(this).attr("fileName");
			if(isChecked == "1"){
				$(this).attr("isChecked","2").next().removeClass("addImg_checked_hide");
				imgList.push(srcId);
				fileList.push({"imgId":srcId,"imgUrl":imgUrl});
				nameList.push(fileName);
			}else if(isChecked == "2"){
				$(this).attr("isChecked","1").next().addClass("addImg_checked_hide");
				imgList.splice($.inArray(srcId,imgList),1);
				nameList.splice($.inArray(fileName,nameList),1);
				for(var  i = 0; i < fileList.length ; i++){
					if(srcId == fileList[i].imgId){
						fileList.splice(i,1);
					}
				}
			}
			infoParams.imgList = imgList;
			infoParams.fileList =fileList;
			infoParams.nameList =nameList;
		});
	};

	/*
	 *	手动上传：
	 */
	var formate = function(d){
		return d>9?d:'0'+d;
	}
	var time = function(d){
		var year=d.getFullYear();
		var day=d.getDate();
		var month=+d.getMonth()+1;
		var hour=d.getHours();
		var minute=d.getMinutes();
		var second=d.getSeconds();
		var f=year+"-"+formate(month)+"-"+formate(day)+" "+formate(hour)+":"+formate(minute)+":"+formate(second);
		return f;
	}
	//加载中图标样式：
	var loading = function(){
		var h = '<div class="upload-pictures-tip">'+
				'	<div class="loader">'+
				'		<div class="ball-spin-fade-loader">'+
				'		    <div></div>'+
				'		    <div></div>'+
				'		    <div></div>'+
				'		    <div></div>'+
				'		    <div></div>'+
				'		    <div></div>'+
				'		    <div></div>'+
				'		    <div></div>'+
				'		</div>'+
				'	</div>'+
				'	<p>图片正在上传中</p>'+
				'</div>';
			$("body").append(h);
	}
	//
	var ajaxSaveWebImgInfoCallBack = function(params,data){
		$bb.toastShow("上传成功",1500);
		//获取代签名的阿里云地址：
		var fileList = [];
		for(var i = 0; i < data.imgList.length;i++){
			fileList.push({
				"imgId":data.imgList[i].imgId,
				"imgUrl":data.imgList[i].imagePath
			});
		}
		var params02 = {"fileList":fileList}
		$imgCollectionServers.getImgSignatureUrl(params02,getManual_ImgUrlCallback,params.infoParams,params.id);
	}
	var uploadMultiFileCallBack03 = function(status,params){
		if( status == 200 ){
			$questionServers.ajaxSaveWebImgInfo(params,ajaxSaveWebImgInfoCallBack);
		}else{
			$("#"+params.id).remove();
			$bb.toastShow("上传失败",1500);
		}
		params.obj.value = "";
	}
	var ajaxPolicyCallBack03 = function(params,policy){
		var infoParams = params.infoParams;
		var fd = new FormData();
    	var filename = $comm.random(5) + $comm.timestamp() + $comm.getSuffix(params.file.name);
        
        fd.append('key', policy.dir + filename);  //存储在oss的文件路径
        fd.append('policy', policy.policy);  //policy
        fd.append('OSSAccessKeyId', policy.accessId);  //accessKeyId
        fd.append('success_action_status', "200");  //成功后返回的操作码
        fd.append('Signature', policy.signature);   //签名
        fd.append("file",params.file);

        var url = window.URL.createObjectURL(params.file);
    	var id = "picture_" + $comm.timestamp() + "_" + $comm.random();
        var h = '<div id="'+ id +'" class="picture" style="background:url(' + url + ') no-repeat center;background-size:cover">'+
            '   <div class="progress-pic"><div></div></div>'+
            '</div>';
        $(infoParams.naturalDom).prev(".qaCard-imageBox").append(h);
        var imgUrl = policy.host + policy.dir + filename;
    	$.extend(params,{
        	"url":policy.host,
        	"fd":fd,
        	"imgUrl":imgUrl,
        	"id":id,
        });

		var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
		var data = {
			"fileList":[
				{
					"fileAuthorName":params.file.name,
					"fileCreateTime":time(new Date(params.file.lastModified)),
					"fileModifyTime":time(new Date(params.file.lastModified)),
					"insideIp":'',
					"outsideIp":'',
					"sourceFilePath":"",
	                "sourceFileName": params.file.name,
	                "fileSize": params.file.size + "",
	                "filePath": imgUrl,
				}
			],
			"oprInfo": {
				"equipFlag":"2",					//2未指定设备；1正常设备；
				"equipId":params.manualTypeId,
				"opCode":"1115", 					//1115门诊上传文件
				"opNote":"【"+sessinonName+"】医生给【"+infoParams.patientName+"】患者上传了【"+ params.file.name +"】图片",
				"opType":"2" 						//2门诊；
			},
			"userInfo": {
				"birthday":infoParams.birthday,
				"gender":infoParams.gender,   //M男，F女
				"hisNo":infoParams.number ? infoParams.number:"",
				"residentAddress":infoParams.residentAddress,//居住地址
				"userId":infoParams.userId
			}
		};
		$.extend(params,{"saveWebImgInfoParams":data});
        $questionServers.uploadFile(params,uploadMultiFileCallBack03);
	}
	var addImg_manualUpload = function(infoParams){
		/*
		//选择正常设备：
		var equipIdList = [];
		$('#equipType-checkbox input[type="checkbox"]:checked').each(function(){
			equipIdList.push($(this).attr("equipId"));
		});
		if(equipIdList.length != 1){
			$bb.toastShow("请先选择上传图片的所属设备编号(只能选择一个设备)",1500);
			infoParams.dom.value = ''; //将value值置空；
			return;
		}*/
		if(infoParams.dom.value != null && infoParams.dom.value != ""){
			var manualTypeId = infoParams.manualTypeId;
			var files = infoParams.dom.files;
			var typeStr = "image/jpg, image/png, image/gif, image/jpeg";
			for (var i = 0; i < files.length; i++){
				if(typeStr.indexOf(files[i].type) == -1){
					$bb.toastShow("请上传格式为jpg、png、gif、jpeg的图片！");
					return;
				}
				$("#modalBox ." + infoParams.className).modal("hide");
				// 直接上传到oss
				var params = {
		    		"obj":infoParams.dom,
		    		"file":files[i],
		    		"infoParams":infoParams,
		    		"manualTypeId":manualTypeId[0],
		    		"type":"1"
		    	};
		    	$questionServers.ajaxPolicy(params,ajaxPolicyCallBack03);
			}
		}
	}
	//手动上传的回调函数：已废
	var addImg_manualUploadCallback = function(data,infoParams,id){
		if( $(".upload-pictures-tip").length > 0 ){
			$(".upload-pictures-tip").remove();
		}
		if(data.success){
			$bb.toastShow("上传成功",1500);
			var imgList = data.data.imgList;
			//获取代签名的阿里云地址：
			var fileList = [];
			for(var i = 0; i < imgList.length;i++){
				var imgId = imgList[i].imgId;
				var filePath = imgList[i].imagePath;
				fileList.push({"imgId":imgId,"imgUrl":filePath});
			}
			var params = {"fileList":fileList}
			$imgCollectionServers.getImgSignatureUrl(params,getManual_ImgUrlCallback,infoParams,id);
		}else{
			$bb.toastShow("上传失败",1500);
		}
	}
	var getManual_ImgUrlCallback = function(data,infoParams,id){
		if(id){
			if( data.success ){
				var imgList = data.data.fileList;
				$("#"+id).attr("imgOldUrl",imgList[0].imgUrl);
				$("#"+id).attr("ImgId",imgList[0].imgId);
				$("#"+id).attr("style","background:url("+imgList[0].imgNewUrl+") no-repeat center;background-size:cover");
				$("#" + id + " .progress-pic > div").html('<i class="fa fa-check-circle" aria-hidden="true"></i>');
			}else{
				$("#"+id).remove();
			}
			delete infoParams.naturalDom;
		}else{
			var imgList = data.data.fileList;
			var h = '';
			for(var i = 0;i < imgList.length ; i++){
				var imgOldUrl = imgList[i].imgUrl;
				h += '<div class="picture"  imgOldUrl = "'+ imgOldUrl +'" style="background:url('+imgList[i].imgNewUrl+') no-repeat center;background-size:cover" ImgId = "'+imgList[i].imgId+'">'+
					'		<div class="picture-box">'+
					'			<span class="imageProcessing-del" ><i class="fa fa-trash-o"></i>删除</span>'+
					'			<span class="imageProcessing-edit" ><i class="fa fa-pencil-square-o"></i>编辑</span>'+
					'		</div>'+
					'	</div>'
			}
			$(infoParams.naturalDom).prev(".qaCard-imageBox").append(h);
			delete infoParams.naturalDom;
		}
	}
	/*
	 * 	自动上传：关联具体的患者：
	 */
	var addImg_autoUpload = function(infoParams){
		var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
		var params = {
			"oprInfo":{
				"opCode":"1116", //1116图片关联具体患者
				"opNote":"【"+sessinonName+"】医生给【"+infoParams.patientName+"】患者关联了【"+ infoParams.nameList.join("、") +"】图片",
				"opType":"2" //2门诊；
			},
			"assInfo":{
				"birthday":infoParams.birthday,
				"gender":infoParams.gender,
				"imgIdList":infoParams.imgList, //文件的id列表；
				"residentAddress":infoParams.residentAddress,//infoParams.residentAddress,//居住地址
				"userId":infoParams.userId
			}
		}
		if(infoParams.imgList.length == 0){
			$bb.toastShow("请先选择要关联的图片",1500);
		}else{
			$imgCollectionServers.imgUploadAuto(params,addImg_autoUploadCallback,infoParams);
		}
	}
	//关联患者与图片的回调函数：
	var addImg_autoUploadCallback = function(data,infoParams){
		if(data.success){
			$bb.toastShow("关联成功",1500);
			var params = {"fileList":infoParams.fileList};
			$imgCollectionServers.getImgSignatureUrl(params,getManual_ImgUrlCallback,infoParams);
			$("#modalBox ." + infoParams.className).modal("hide");
			delete infoParams.fileList;
			delete infoParams.nameList;
		}else{
			$bb.toastShow("关联失败",1500);
		}
	}
	/*
	 * 查询影像文件：
	 * */
	var addImg_searchBtn = function(infoParams){
		var equipIdList = [],manualTypeId = infoParams.manualTypeId ;
		if($(".manul-label").find('input:checked').length > 0){
			equipIdList = equipIdList.concat(manualTypeId);
		}else{
			equipIdList.splice($.inArray(manualTypeId[0],equipIdList),1);
		}
		
		$('#equipType-checkbox input[type="checkbox"]:checked').each(function(){
			equipIdList.push($(this).attr("equipId"));
		});

		var inParams = {
			"beginTime":$.trim($("#addImg_beginTime").val()),
			"endTime":$.trim($("#addImg_endTime").val()),
			"equipIdList":equipIdList,
			"hisNo":infoParams.number,
			"page":infoParams.page,
			"rows":infoParams.rows,
			"userId": infoParams.userId,  
			"userName":infoParams.patientName,//
			"fileType":"0",
			"imgId":""
		};
		if(equipIdList.length == 0){
			$bb.toastShow("请先选中要查询的设备编号！",1500);
		}else{
			$imgCollectionServers.getImgList(inParams,getImgListCallback,infoParams);
		}
	};
	/*
	 * 查询影像文件的回调函数：getImgListCallback
	 */
	//图片的选中状态处理：
	var imgfileDeal = function(data,imgList){
		for(var i = 0; i< data.rows.length;i++){
			var imgId = data.rows[i].id;
			var sourceFileName = data.rows[i].sourceFileName;
			var fileType = data.rows[i].fileType;
			data.rows[i].sourceFileName2 = sourceFileName.substring(0,sourceFileName.indexOf(fileType)-1);
			data.rows[i].fileSize2 = (data.rows[i].fileSize/1024).toFixed(2);//字节转换为k
			if($.inArray(imgId,imgList) >= 0){
				data.rows[i].checked = 2; //选中状态；
			}else{
				data.rows[i].checked = 1; //未选中状态；
			}
		}
	}
	//获取带签名的阿里云地址：
	var getImgSignatureUrl = function(data,otherParams){
		var fileList = [];
		for(var i = 0; i< data.rows.length;i++){
			var imgId = data.rows[i].id;
			var filePath = data.rows[i].filePath;
			fileList.push({"imgId":imgId,"imgUrl":filePath});
		}
		var params = {"fileList":fileList}
		data.className = otherParams.className;
		$imgCollectionServers.getImgSignatureUrl(params,getImgSignatureUrlCallback,data);
	}
	//获取带签名的阿里云地址的回调
	var getImgSignatureUrlCallback = function(data,otherParams){
		//将返回的新的url合并到之前的数据；
		var fileList = data.data.fileList;
		for(var i = 0;i< fileList.length;i++){
			var id = fileList[i].imgId;
			var imgNewUrl = fileList[i].imgNewUrl;
			var imgOldUrl = fileList[i].imgUrl;
			for(var k = 0 ;k < otherParams.rows.length ; k++){
				if( otherParams.rows[k].id == id && otherParams.rows[k].filePath == imgOldUrl){
					otherParams.rows[k].imgNewUrl = imgNewUrl;
				}
			}
		}
		$questionUi.addImg_imageBoxInit({
			"dom":$("#modalBox ." + otherParams.className + " .modal-body #add-imageProcessing-imageBox"),
			"data":otherParams
		});
	}
	var getImgListCallback = function(data,infoParams){
		if(data.data.total > 0){
			imgfileDeal(data.data,infoParams.imgList);
			getImgSignatureUrl(data.data,infoParams);
			var pages = Math.ceil(data.data.total/infoParams.rows),page = infoParams.page;
			$page.init({
				id:"btn-toolbar",
				pagesAll:pages,
				page:page
			});
			$("#btn-toolbar .btn").click(function(){
				var text = $(this).text();
				page = $page.getPageActive({
					"pageClick":text,
					"page":page,
					"pagesAll":pages
				});
				infoParams.page = page*1;
				addImg_searchBtn(infoParams);
			});
		}else{
			$questionUi.addImg_imageBoxInit({
				"dom":$("#modalBox ." + infoParams.className + " .modal-body #add-imageProcessing-imageBox"),
				"data":data.data
			});
			$("#btn-toolbar").html("");
		}
	};

	/**
	 * 影像处理_编辑
	 */
	var getImgSignatureUrlCallback_edit = function(data,params){
		if(data.success){
			params.imgSrc = data.data.fileList[0].imgNewUrl;
			$comm.modal({
				"tit":"图像处理",
				"size":"modal-lg",
				"className":params.className
			},function(){
				$questionUi.editImageProcessingInit({
					"dom":$("#modalBox ." + params.className + " .modal-body"),
					"data":{"fileName":params.fileName}
				});
				$drawCanvas.init(params.imgSrc,params);
				$("#modalBox ." + params.className).modal("show");
			});
		}
	}
	var getImgDetailCallback = function(data,params){
		if(data.success){
			var imgInfo = data.data.rows[0];
			params.equipId = imgInfo.equipId;
			params.fileName = imgInfo.sourceFileName;
			params.rotationAngle = imgInfo.rotationAngle;
			var inParams = {"fileList":[{"imgId":imgInfo.id,"imgUrl":imgInfo.filePath}]}
			$imgCollectionServers.getImgSignatureUrl(inParams,getImgSignatureUrlCallback_edit,params);
		}
	}
	var imageProcessingEdit = function(params){
		var className = "imageProcessingModal";
		params.className = className;
		params.imgId = $(params.dom).parents(".picture").attr("imgId");
		params.markIdList = $(params.dom).parents(".picture").attr("markIdList");
		params.diseaseTypeId = JSON.parse($(params.dom).parents(".qaCard-imageBox").siblings('.imageProcessing-addBtn').attr("diseaseTypeId"));
		var inParams = {
			"imgId":params.imgId
		}
		$imgCollectionServers.getImgList(inParams,getImgDetailCallback,params);
	}
	/**
	 * 影像处理_删除：
	 */
	var imageProcessingDel = function(params){
		$bb.toastConfirmShow(imageProcessingDel_sureCallback,params,"确定要删除该图片么？");
	}
	// "确定删除"的回调函数；
	var imageProcessingDel_sureCallback = function(params){
		var imgId = $(params.dom).parents(".picture").attr("imgId");
		var inParams = {
			"imgId":imgId
		}
		var deleteImage = function(data,params){
			if(data.success){
				var sessinonName = JSON.parse($bb.getSessionStorage("account")).alias;
				var fileName = data.data.rows[0].sourceFileName;
				//入参：
				var inParams = {
					"oprInfo":{
						"opCode":"1117", //1117 解除图片与患者的关联关系
						"opNote":"医生【"+sessinonName+"】解除了【"+params.patientName+"】患者与【"+ fileName +"】图片的关联",
						"opType":"2" //2门诊；
					},
					"assInfo":{
						"imgId":imgId, //文件的id列表；
						"userId":params.userId
					}
				}
				$imgCollectionServers.imgDel(inParams,imageProcessingDelCallback,params);
			}
		}
		$imgCollectionServers.getImgList(inParams,deleteImage,params);
	}
	//图片删除的回调函数：
	var imageProcessingDelCallback = function(data,infoParams){
		if(data.success){
			$bb.toastShow("删除成功！",1500);
			$(infoParams.dom).parents("div.picture").remove();
			delete infoParams.dom;
		}else{
			$bb.toastShow("删除失败！",1500);
		}
	}
	// 鼠标经过.picture，.picture里的div显示，离开隐藏
	var imageProcessingImgShow = function(){
		$(".qaCard-imageProcessing").on("mouseenter",".picture",function(){
			$(this).children("div.picture-box").slideDown();
		});
		$(".qaCard-imageProcessing").on("mouseleave",".picture",function(){
			$(this).children("div.picture-box").slideUp();
		});
	}
	/**
	 * 影像处理 图片
	 */
	var imageProcessing = function(params){
		imageProcessingImgShow();
		// 添加
		$(".qaCard-imageProcessing .imageProcessing-addBtn").unbind("click");
		$(".qaCard-imageProcessing .imageProcessing-addBtn").data({"this":this});
		$(".qaCard-imageProcessing .imageProcessing-addBtn").click(function(){
			params.dom = this;
			params.naturalDom = this;
			imageProcessingAdd(params);
		});
		// 编辑
		$(".qaCard-imageProcessing").off("click",".imageProcessing-edit");
		$(".qaCard-imageProcessing").on("click",".imageProcessing-edit",function(){
			params.dom = this;
			imageProcessingEdit(params);
		});
		//删除
		$(".qaCard-imageProcessing .imageProcessing-del").off("click",".imageProcessing-del");
		$(".qaCard-imageProcessing").on("click",".imageProcessing-del",function(){
			params.dom = this;
			imageProcessingDel(params);
			
		});
	}
	// 离线影像处理
	var imageProcessingOffline = function(){
		imageProcessingImgShow();
		// 添加
		$(".qaCard-imageProcessing .imageProcessing-addBtn").unbind("click");
		$(".qaCard-imageProcessing .imageProcessing-addBtn").click(function(){
			$bb.toastShow("离线版暂不支持影像添加！",1500);
		});
		// 编辑
		$(".qaCard-imageProcessing").off("click",".imageProcessing-edit");
		$(".qaCard-imageProcessing").on("click",".imageProcessing-edit",function(){
			$bb.toastShow("离线版暂不支持影像编辑！",1500);
		});
		//删除
		$(".qaCard-imageProcessing .imageProcessing-del").off("click",".imageProcessing-del");
		$(".qaCard-imageProcessing").on("click",".imageProcessing-del",function(){
			$bb.toastShow("离线版暂不支持影像删除！",1500);
		});
	}

	/**
	 * 九宫格题型
	 */
	var sudoku = function(){
		$(".qaCard-sudoku .sudoku .sudoku-dropdown-toggle.clickable").click(function(e){
			e.stopPropagation();
			var This = this;
			$(This).parent().next().toggle();
			$(This).parent().next().find("li").click(function(e){
				e.stopPropagation();
			});
			$(This).parent().next().find("li.clickable").click(function(){
				$(this).addClass("active").siblings().removeClass("active");
				var value = $(this).html();
				$(This).prev().val(value);
				$(This).parent().next().hide();
			});
		});
		$(".qaCard-sudoku .sudoku input").bind("input propertychange",function(){
			var value = $(this).val();
			var oLi = $(this).parent().next().find("li.clickable");
			oLi.each(function(i){
				if( oLi.eq(i).html() == value ){
					oLi.eq(i).addClass("active");
				}else{
					oLi.eq(i).removeClass("active");
				}
			});
		});
		$(document).click(function(){
			$(".qaCard-sudoku .sudoku .sudoku-dropdown").hide();
		});
	}
	/**
	 * question_geneFusion 题型
	 */
	// 添加项目成功后的回调函数
	var ajaxAddProjectItemCallBack = function(data,dataParams){
		$.extend(dataParams.params,{"flag":true});
		geneFusion(dataParams.params);
	}
	// 点击"添加项目"，出现表单；点击保存，进行添加项目
	var onAddProjectItemSave = function(){
		var alias = JSON.parse( $bb.getSessionStorage("account") ).alias;
		var This = this;
		var data = $(this).data();
		$(this).hide().next().show();
		$(this).next().children(".add-projectItem-saveBtn").click(function(){
			var configName = $(This).next().find("input[name=configName]").val();
			var params = {
				"oprInfo":{
					"opCode":"2013",
			        "opNote":"【"+ alias +"】医生添加了【"+ configName +"】项目",
			        "opType":"3",
				}, 
			    "projectInfo":{
			    	"configCode":data.configParams.configCode,
			    	"configType":data.configParams.configType,
			        "configName":configName,
			        "queueId":data.params.followQueueId,
			        //"hisCode":""
			    } 	
			};
			$questionServers.ajaxAddProjectItem(data,params,ajaxAddProjectItemCallBack);
		});
	}
	// 更新项目成功后的回调函数
	var ajaxUpdateProjectItemCallBack = function(data,dataParams){
		$.extend(dataParams.params,{"flag":true});
		geneFusion(dataParams.params);
	}
	// 更新项目
	var onProjectItemUpdate = function(){
		var data = $(this).data();
		var alias = JSON.parse( $bb.getSessionStorage("account") ).alias;
		var configName = $(this).parent("li").children("span").html();
		var configCode = $(this).parent("li").attr("configCode");
		var configType = $(this).parent("li").attr("configType");
		var id = $(this).parent("li").attr("id");
		var showFlag = $(this).parent("li").attr("showFlag");
		showFlag = showFlag == "01" ? "00" : "01";
		var params = {
			"oprInfo":{
				"opCode":"2015",
		        "opNote":"【"+ alias +"】医生修改了【"+ configName +"】项目",
		        "opType":"3"
			}, 
		    "projectInfo":{
		    	"configCode":configCode,
		        "configType":configType,
		        "id":id,
		        "showFlag":showFlag
		    }
		};
		$questionServers.ajaxUpdateProjectItem(data,params,ajaxUpdateProjectItemCallBack);
	}
	// 删除项目成功后的回调函数
	var ajaxDelProjectItemCallBack = function(data,dataParams){
		$.extend(dataParams.params,{"flag":true});
		geneFusion(dataParams.params);
	}
	// 删除项目
	var onProjectItemDel = function(){
		var data = $(this).data();
		var alias = JSON.parse( $bb.getSessionStorage("account") ).alias;
		var configName = $(this).parent("li").children("span").html();
		var configCode = $(this).parent("li").attr("configCode");
		var configType = $(this).parent("li").attr("configType");
		var id = $(this).parent("li").attr("id");
		var params = {
			"oprInfo":{
				"opCode":"2014",
		        "opNote":"【"+ alias +"】医生删除了【"+ configName +"】项目",	
		        "opType":"3"
			},  
		    "projectInfo":{
		    	"configCode":configCode,
		        "configType":configType,
		        "id":id
		    }  
		}
		$questionServers.ajaxDelProjectItem(data,params,ajaxDelProjectItemCallBack);
	}
	// 点击问卷里的“融合基因常用项目管理”按钮触发的事件
	var onGeneFusionManager = function(){
		var data = $(this).data();
		var className = "geneFusionModal";
		$comm.modal({
			"className": className,
            "size": "modal-sm",
            "tit": data.configParams.btnText,
		},function(){
			$questionUi.projectItemManagerInit({
				"dom":$("." + className + " .modal-body"),
				"list":data.rows
			});
			$("." + className).modal("show");
			var transferParams = {
				"params":data.params,
				"configParams":data.configParams,
				"className":className
			};
			// 更新项目
			$("." + className + " .projectItem-box li i.projectItem-show").unbind("click");
			$("." + className + " .projectItem-box li i.projectItem-show").data(transferParams);
			$("." + className + " .projectItem-box li i.projectItem-show").click(onProjectItemUpdate);
			// 添加项目
			$("." + className + " .add-projectItem-btn").unbind("click");
			$("." + className + " .add-projectItem-btn").data(transferParams);
			$("." + className + " .add-projectItem-btn").click(onAddProjectItemSave);
			// 删除项目
			$("." + className + " .projectItem-box li i.projectItem-del").unbind("click");
			$("." + className + " .projectItem-box li i.projectItem-del").data(transferParams);
			$("." + className + " .projectItem-box li i.projectItem-del").click(onProjectItemDel);
		});
	}
	// 获取disabled为true的list(list为下拉框)的text的集合
	var getDisabledItem = function(list){
		var arr = [];
		for (var i = 0; i < list.length; i++) {
			if( list[i].disabled == true ){
				arr.push(list[i].text);
			}
		}
		return arr;
	}
	// select和input的关联 (select变化，input相应变化)
	var relevantSelectInput = function(list,obj){
		var disabledItem = getDisabledItem(list);
		obj.find(".qaCard").each(function(){
			var val = $(this).find(".control-input select").val();
			if( $.inArray(val,disabledItem) > -1 ){
				$(this).find(".control-input input").attr("disabled","disabled");
			}else{
				$(this).find(".control-input input").removeAttr("disabled");
			}
		});
		obj.find(".qaCard .control-input select").change(function(){
			var val = $(this).val();
			if( $.inArray(val,disabledItem) > -1 ){
				$(this).next().attr("disabled","disabled");
			}else{
				$(this).next().removeAttr("disabled");
			}
		});
	}
	// 初始化数据处理(values为保存的结果)
	var projectItemHandel = function(list,values){
		for (var i = 0; i < list.length; i++) {
			for(var key in values){
				if( list[i].id == key ){
					list[i].val = JSON.parse(values[key]);
					list[i].val1 = list[i].val[0];
					list[i].val2 = list[i].val[1];
				}
			}
		}
		return list;
	}
	// 请求题目成功后的回调函数
	var ajaxQueryProjectItemCallBack = function(data,configParams,obj,params){
		$questionUi.projectItemInit({
			"dom":obj,
			"list":projectItemHandel(data.rows,params.values),
			"configParams":configParams,
		});
		relevantSelectInput(configParams.list,obj);
		obj.find(".geneFusion-manager-btn").unbind("click");
		obj.find(".geneFusion-manager-btn").data({
			"configParams":configParams,
			"rows":data.rows,
			"params":params
		});
		obj.find(".geneFusion-manager-btn").click(onGeneFusionManager);
		if(params && params.flag){
			obj.find(".geneFusion-manager-btn").click();
		}
	}
	// 融合基因题型
	var geneFusion = function(params){
		var dom = $(".qaCard-geneFusion");
		dom.each(function(i){
			var configParams = JSON.parse($(this).attr("configParams"));
			if( $bb.getIocalStorage("version") == "online" ){
				$questionServers.ajaxQueryProjectItem(configParams,$(this),ajaxQueryProjectItemCallBack,params);
			}else{
				var tips = (configParams && configParams.btnText) ? "【"+configParams.btnText+"】" : "";
				$(this).html('<div class="qaCard-geneFusion-offline">离线版暂不支持该'+ tips +'题型</div>');
			}
		});
	}

	/**
	 * 九宫格图片
	 */
	// 删除图片
	var onDelSudokuPic = function(){
		var name = $(this).parents(".qaCard-sudokuPic-box").attr("name");
		var h = '<div class="upload">'+
				'	<div class="upload-bg">'+
				'		<i class="fa fa-plus"></i>'+
				'		<span>点击添加影像</span>'+
				'	</div>'+
				'	<input class="form-control validatebox" type="file" name="'+ name +'">'+
				'</div>';
		$(this).parents(".qaCard-sudokuPictures").html(h);
		$(".qaCard-sudokuPictures .upload input[type=file]").unbind("change");
		$(".qaCard-sudokuPictures .upload input[type=file]").change(onSudokuPicUpload);
	}
	// 上传图片成功后的回调
	var sudokuPicUploadCallBack = function(status,params){
		if( status == 200 ){
			$("#"+params.id).attr("data-value",params.imgUrl);
			$("#"+params.id).attr("style","background:url(" + params.imgUrl + "?x-oss-process=image/resize,h_100) no-repeat center;background-size:cover");
			$("#" + params.id + " .progress-pic > div").html('<i class="fa fa-check-circle" aria-hidden="true"></i>');
			$(".qaCard-pictures .picture").click(onPhotoZoomPro);
		}else{
			$("#"+params.id).parents(".qaCard-sudokuPictures").html(params.h2);
		}
		params.obj.value = "";
	}
	// 请求policy成功后的回调函数
	var ajaxPolicyCallBack02 = function(params,policy){
		var fd = new FormData();
    	var filename = $comm.random(5) + $comm.timestamp() + $comm.getSuffix(params.file.name);
    	var imgUrl = policy.host + policy.dir + filename;
        
        fd.append('key', policy.dir + filename);  //存储在oss的文件路径
        fd.append('policy', policy.policy);  //policy
        fd.append('OSSAccessKeyId', policy.accessId);  //accessKeyId
        fd.append('success_action_status', "200");  //成功后返回的操作码
        fd.append('Signature', policy.signature);   //签名
        fd.append("file",params.file);

        var url = window.URL.createObjectURL(params.file);
    	var id = "picture_" + $comm.timestamp() + "_" + $comm.random();
        var h = '<div id="'+ id +'" class="picture" style="background:url(' + url + ') no-repeat center;background-size:cover">'+
            '   <div class="progress-pic"><div></div></div>'+
            '</div>';
        var h2 = $(params.obj).parents(".qaCard-sudokuPictures").html();
        $(params.obj).parents(".qaCard-sudokuPictures").html(h);
        $.extend(params,{
        	"url":policy.host,
        	"fd":fd,
        	"imgUrl":policy.host + policy.dir + filename,
        	"id":id,
        	"h2":h2
        });
        $questionServers.uploadFile(params,sudokuPicUploadCallBack);
	}
	// 上传图片
	var onSudokuPicUpload = function(){
		if( $bb.getIocalStorage("version") == "online" ){
			var obj = this;
    		if(obj.value != null && obj.value != ""){
		    	var typeStr = "image/jpg, image/png, image/gif, image/jpeg";
		    	var files = obj.files;
		    	for (var i = 0; i < files.length; i++) {
		    		if(typeStr.indexOf(files[i].type) == -1){
				        $bb.toastShow("请上传格式为jpg、png、gif、jpeg的图片！");
				        return;
				    }
				    if (files[i].size >= 1024*1024*10) {
				        $bb.toastShow("上传的文件不能大于10M！");
				        return;
				　　}
					// 直接上传到oss
					var params = {
			    		"obj":obj,
			    		"file":files[i],
			    	};
			    	$questionServers.ajaxPolicy(params,ajaxPolicyCallBack02);
		    	}
	    	}
	    }else{ // 离线版
    		$bb.toastShow("离线版暂不支持上传图片！");
		}
	}
	// 九宫格图片
	var sudokuPictures = function(){
		// 上传图片
		$(".qaCard-sudokuPictures .upload input[type=file]").unbind("change");
		$(".qaCard-sudokuPictures .upload input[type=file]").change(onSudokuPicUpload);
		// 放大
		$(".qaCard-sudokuPictures .picture").click(onPhotoZoomPro);
		$(".qaCard-sudokuPictures .picture .picture-del-box").click(function(){ return false; });
		// 删除
		$(".qaCard-sudokuPictures .picture").mouseenter(function(){
			$(this).find(".picture-del-box").slideDown();
			$(this).find(".picture-del").click(onDelSudokuPic);
		}).mouseleave(function(){
			$(this).find(".picture-del-box").slideUp();
		});
	}

	/**
	 * 事件初始化
	 */
	questionEvent.init = function(options){
		iconShow();
		gestationComplex();
		gestationSimple();
		if(options && options.getGrowth){
			growth(options.getGrowth);
		}
		if(options && options.getPatientsByPhone){
			getPatientsByPhone(options.getPatientsByPhone);
		}
		radioInput();
		checkboxInput();
		cancelRadioChecked();
		address();
		if(options && options.getTextareaAssess){
			textareaAssess(options.getTextareaAssess); 
		}
		checkboxRelation();
		radioRelation();
		correctAge();
		overallBirth();
		checkboxWithInput();
		radioWithInput();
		collapse();
		uploadPictures();
		karteName();
		if( $bb.getIocalStorage("version") == "online" ){
			if(options && options.getImageProcessing){
				imageProcessing(options.getImageProcessing);
			}
		}else{
			imageProcessingOffline();
		}
		sudoku();
		// 融合基因
		if(options && options.getGeneFusion){
			geneFusion(options.getGeneFusion);
		}else{
			geneFusion();
		}
		sudokuPictures();
	};

	return questionEvent;
});